from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import request
from flask import session
from flask import url_for
from info.models import Category, User
from info import constants
from info import db
from info.models import News
from info.modules.index.views import index
from info.utils.commons import user_login_data
from info.utils.image_storage import image_storage
from info.utils.response_code import RET
from . import profile_blue
from flask import render_template

# 功能分析：获取我的关注列表
# 访问路径：/user/user_follow
# 请求方式:GET
# 请求参数：无
# 返回值：html页面＆data
@profile_blue.route('/user_follow')
@user_login_data
def user_follow():

    # 获取参数
    page = request.args.get('p','1')

    # 数据类型转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 分页查询用户关注列表
    try:
        paginate = g.user.followed.paginate(page,4,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='获取关注列表失败')

    currentPage = paginate.page
    totalPage = paginate.pages
    items = paginate.items

    followed_list = []
    for item in items:
        followed_list.append(item.to_dict())

    data = {
        'currentPage':currentPage,
        'totalPage':totalPage,
        'followed_list':followed_list
    }


    return render_template('news/user_follow.html',data=data)



# 功能分析：获取作者新闻列表，要理解这个请求是从哪里发过来的，什么时候访问这个接口
# 请求方式:GET
# 请求路径：user/other_news_list
# 请求参数：author_id,page
# 返回值：data
@profile_blue.route('/other_news_list')
def other_news_list():

    # 获取参数
    page = request.args.get('p','1')
    author_id = request.args.get('user_id')

    # 强制类型转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    if not author_id: return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    # 根据作者id取出作者对像
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='获取作者失败')

    if not author: return jsonify(errno=RET.NODATA,errmsg='该作者不存在')

    # 获取数据库新闻
    try:
        # paginate = News.query.filter(News.user_id == author_id).order_by(News.create_time.desc()).paginate(page,10,False)
        # 根据作者发布的新闻查询
        paginate = author.news_list.order_by(News.create_time.desc()).paginate(page,3,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='作者新闻列表查询失败')

    currentPage = paginate.page
    totalPage = paginate.pages
    items = paginate.items

    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    data = {
        "current_page":currentPage,
        "total_page":totalPage,
        'news_list':news_list
    }

    return jsonify(errno=RET.OK,errmsg='获取成功',data=data)


# 功能描述：获取作者详情,要理解这个请求是从哪里发过来的，什么时候访问这个接口
# 请求路径：user/other
# 请求方式：get
# 请求参数：user_id
# 返回值：html页面＆data数据
@profile_blue.route('/other')
@user_login_data
def other():

    # 获取参数user_id
    author_id = request.args.get('user_id')

    if not author_id:
        return jsonify(errno=RET.NODATA,errmsg='请求参数不全')

    # 根据用户id获取用户对象
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='获取作者信息失败')

    # 判断客户是否存在
    if not author: return jsonify(errno=RET.NODATA,errmsg='该作者不存在')

    is_follow = False
    if g.user and g.user in author.followers:
        is_follow = True


    data = {
        'user_info':g.user.to_dict() if g.user else '',
        'author':author.to_dict(),
        'is_follow':is_follow
    }

    return render_template('news/other.html',data=data)


# 功能分析：获取新闻的发布列表
# 请求方式：GET
# 请求路径：/user/news_list
# 请求参数:p
# 返回值：html页面，data
@profile_blue.route('/news_list', methods=['GET', 'POST'])
@user_login_data
def news_list():

    # 获取参数
    page = request.args.get('p','1')
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 分页查询新闻发布列表
    try:
        paginate = News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page,3,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取发布新闻失败')

    currentPage = paginate.page
    totalPage = paginate.pages
    items = paginate.items

    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())

    data = {
        'totalPage':totalPage,
        'currentPage':currentPage,
        'news_list':news_list
    }

    return render_template('news/user_news_list.html',data=data)


#新闻发布
# 请求方式：GET,POST
# 请求路径：/user/news_release
# 请求参数：GET:无，POST:title,category_id,digest,index_image,content
# 返回值：html,data字典
@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_reslease():
    # 判断请求方式,GET返回分类字典
    if request.method == 'GET':

        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR,errmsg='新闻分类获取失败')

        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        return render_template('news/user_news_release.html',categories=category_list)

    # 如果是POST请求，获取参数
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')

    if not all([title,category_id,digest,content]):
        return jsonify(errno=RET.DATAERR,errmsg='请求参数不全1')

    # 上传图片,并判断是否上传成功
    try:
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传失败")

    if not image_name: return jsonify(errno=RET.NODATA, errmsg="图片上传失败")

    # 创建新闻对象,设置新闻属性
    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1  # 审核中

    # 保存新闻到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="新闻发布失败")

    # 返回响应
    return jsonify(errno=RET.OK, errmsg="新闻发布成功")


# 收藏新闻
# 请求方式：GET
# 请求路径:/user/collection
# 请求参数：page
# 返回值：user_collection的html页面和data数据
@profile_blue.route('/collection', methods=['GET', 'POST'])
@user_login_data
def user_collection():
    # 获取参数
    page = request.args.get('p','1')

    # 页数数据类型转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 分页查询客户收藏的新闻
    try:
        paginate = g.user.collection_news.order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='收藏新闻查询失败')

    # 获取当前页数，总页数，当前页对象列表
    currentPage = paginate.page
    totalPage = paginate.pages
    items = paginate.items

    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    data = {
        'currentPage':currentPage,
        'totalPage':totalPage,
        'news_list':news_list
    }

    return render_template('news/user_collection.html',data=data)


# 功能分析：用户密码更改
# 请求方式：GET,POST
# 请求路径：/user/pass
# 请求参数，无
# 返回值：html页面
@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def user_pass():

    # 如果是GET请求方式，直接返回页面
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    # 不为空判断
    if not all([old_password,new_password]):
        return jsonify(errno=RET.DATAERR,errmsg='密码不能为空')

    # 校验密码是否正确
    if not g.user.check_password(old_password):
        return jsonify(errno=RET.DATAERR,errmsg='密码不正确')

    try:
        g.user.password = new_password
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR,errmsg='密码更改失败')
    # 清除session数据
    session.pop('user_id',None)
    session.pop('mobile',None)
    session.pop('nick_name',None)

    return jsonify(errno=RET.OK,errmsg='密码更改成功')


# 功能分析：上传图片
# 访问路径：/user/pic_info
# 访问路径:GET,POST
# 请求参数：get.无,post,file
# 返回值:html页面
@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():

    # 判断请求方式,如果是GET请求，直接携带用户数据渲染页面
    if request.method == 'GET':
        data = {
            'user_info':g.user.to_dict() if g.user else ''
        }
        return render_template('news/user_pic_info.html',data=data)

    # 获取参数,request.files获取到的是图片二进制留
    avatar = request.files.get('avatar')

    # 上传到七牛云
    try:
        image_name = image_storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='七牛云异常')

    # 判断地址是否存在
    if not image_name: return jsonify(errno=RET.NODATA,errmsg='图片上传失败')

    # 设置图片到用户对象
    g.user.avatar_url = image_name

    # 返回响应
    data = {
        'avatar_url':constants.QINIU_DOMIN_PREFIX+image_name
    }
    return jsonify(errno=RET.OK,errmsg='头像上传成功',data=data)



# 功能分析：用户基本信息展示＆更改
# 访问方式是：GET,POST
# 访问路径：/user/base_info
# 请求参数：无
# 返回值：HTML页面
@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():

    # 获取用户信息返回html页面
    if request.method == 'GET':
        return render_template('news/user_base_info.html',user_info=g.user.to_dict())

    # 如果访问方式是POST,获取参数
    signature = request.json.get('signature')
    nick_name = request.json.get('nick_name')
    gender = request.json.get('gender')

    # 参数判断
    if not all([nick_name,gender,signature]):
        return jsonify(errno=RET.DATAERR,errmsg='请求参数不全')

    # 判断gender的参数
    if not gender in ['MAN','WOMAN']:
        return jsonify(errno=RET.DATAERR,errmsg='性别不正确')

    # 提交
    try:
        g.user.signature = signature
        g.user.nick_name = nick_name
        g.user.gender = gender
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR,errmsg='更改失败')

    # 返回响应
    return jsonify(errno=RET.OK,errmsg='操作成功')



# 功能分析：用户中心
# 请求方式是：get
# 请求路径：/user/info
# 请求参数：无
# 返回值:HTML页面
@profile_blue.route('/info')
@user_login_data
def user_info():

    # 如果客户不存在，重定向回到首页
    if not g.user:

        return redirect(url_for('index.index'))

    data = {
        'user_info':g.user.to_dict()
    }

    return render_template('news/user.html',data=data)